/**
 * This file is part of iSecurePasswords.
 *
 *   iSecurePasswords is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   iSecurePasswords is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with iSecurePasswords.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Author: Matthew MacGregor
 * Created: 2012
 * iSecurePasswords, copyright 2013 Sudolink, LLC
 * 
 */ 
package com.sudolink.isp.ui;

import com.sudolink.io.JsonExportImport;
import com.sudolink.isp.app.Application;
import com.sudolink.isp.tasks.BackupTask;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author matsu
 */
public class JSONExportForm extends JSONImportExportForm {

    /**
     * Creates new form NewJDialog
     */
    public JSONExportForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(parent);
        setTitle("Export JSON");
        cbOverwrite.setToolTipText(
                "When checked, the destination file will be"
                + " replaced with the data you're exporting."
        );
        lblNotificationArea.setText("");
        lblMessage.setText(
                "<html>Exports passwords to a properly formatted JSON "
                + "file. <b>Please note that this file is not encrypted!"
                +"</b></html>"
        );
        
        String pathToDb = Application.getPathToDatabase();
        this.txtPath.setText(pathToDb + ".json");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 590, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 205, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    @Override
    public void process() {
        new BackupTask().run();
        String tf = txtPath.getText();
        String filename = ( tf.endsWith(".json") ) ? tf : tf + ".json" ;
        File path = new File(filename);
        JsonExportImport jio = new JsonExportImport(path);
        try {
            jio.exportToJson(cbOverwrite.isSelected());
            JOptionPane.showMessageDialog(this, "Your data has been successfully exported.");
            setVisible(false);
            dispose();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Writing to the file has failed."
                    + " Are you sure that you have permission to write to that " 
                    + "location?");
        }

        if( callback != null ) {
            callback.actionPerformed(null);
        }
    }

    @Override
    protected void doClick(ActionEvent evt) {
        File f = new File(getPath());
        if (f.exists() == false || isOverwrite() ) {
            //this.setVisible(false);
            process();
        } else {
            lblNotificationArea.setForeground(Color.red);
            lblNotificationArea.setText("The file already exists. Make sure the 'overwrite' option is selected.");
        }
    }

    @Override
    protected void doBrowse(ActionEvent evt) {
        //Create a file chooser
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        //In response to a button click:
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String _path = fc.getSelectedFile().getAbsolutePath();
            if (!_path.isEmpty()) {
                txtPath.setText(_path);
                txtPath.setForeground(Color.black);
                lblNotificationArea.setText("");
            }

        }   
    }
}
